#include<vector>
using namespace std;

class Solution {
public:
    bool validUtf8(vector<int>& data) {
        vector<int> nums = { 0x00,0xc0,0xe0,0xf0 };
        int mask = 0xff;
        int index = 0;
        while (index < data.size()) {
            int n = 3;
            int tmp = data[index] & mask;
            while (n >= 0) {
                if (tmp >= nums[n])
                    break;
                --n;
            }
            if (n != 0) {
                if (tmp >= (nums[n] + (1 << (6 - n))))
                    return false;
            }
            else {
                if (tmp >= 0x80)
                    return false;
            }
            ++index;
            while (index < data.size()&&n>0) {
                tmp = data[index++] & mask;
                if (tmp >= 0x80 && tmp < 0xc0)
                    --n;
                else
                    break;
            }
            if (n != 0)  return false;

        }
        return true;
    }
};
